#!/usr/bin/python3
# -*- coding:utf-8 -*-
""""
@Author: 李吉凯
@Email: lijk34925@hundsun.com
@Time: 2021/11/5 9:28
@File: views.py
"""
from threading import Thread

from django.contrib import auth
from django.contrib.auth.models import User, Group

from django.http import HttpResponseRedirect, JsonResponse
from djangoProject.settings import BASE_DIR
from job.src.function.basic_opration import rewritefile

from job.views import webPage
from job.src.function.record_log import mylog

from django.shortcuts import render, HttpResponse, redirect
from django.http import StreamingHttpResponse

from django.utils.encoding import escape_uri_path
import os

from markdown.form import LoginForm



def index(request):
    return HttpResponseRedirect('/main/')


def restartPriject(request):
    thread_05 = Thread(target=rewritefile, args=(0.5,))
    thread_05.start()
    return JsonResponse({"res": "系统重启成功，等待1s后刷新页面！\r\n重启成功之后要启动定时任务（必要）和代理服务（非必要）！"})

def login(request):
    context = {}
    context.update(webPage)
    if request.method == 'GET':
        next_url = request.GET.get('next', '/main/')
        context['next_url'] = next_url
        # context.update({"res_info": "Tip：首次登录，即可用输入用户名注册！"})
        return render(request, 'login.html', context)
    username = request.POST.get("username")
    password = request.POST.get("password")
    next_url = request.POST.get("next")
    form = LoginForm(request.POST)
    # if 验证成功返回user对象,否则返回None
    if form.is_valid():
        Pbbool = User.objects.filter(username=username).exists()
        if not Pbbool:
            email = username + "@hundsun.com"
            User.objects.create_user(username=username, password='111111', email=email, is_staff=True)
            context.update({"res_info": f"用户名：{username}，默认密码：111111；注册成功，重新登录！"})
            # 给用户添加组，除AUTH组
            groups = Group.objects.exclude(name__istartswith='AUTH').all()
            user = User.objects.filter(username=username).first()
            for g in groups:
                mylog.info(f"group: {g},{g.id},{g.name}")
                user.groups.add(g.id)
            user.save()
            return render(request, 'login.html', context)
        user = auth.authenticate(username=username, password=password)
        mylog.info(user)
        if user:
            auth.login(request, user)  # request.user:当前登录对象
            next_url = next_url if next_url else '/main/'
            response = redirect(next_url)
            response.set_cookie('name', username, max_age=7 * 24 * 3600)
            return response
        else:
            context.update({"res_info": f"用户名：{username}或密码：{password}不正确！"})
        return render(request, 'login.html', context)
    else:
        context.update({"res_info": f"请检查，用户名：'{username}'不为空或密码:'{password}'不小于5位！"})
        return render(request, 'login.html', context)


def logout(request):
    auth.logout(request)
    return redirect("/login/")

def file_down(request):
    """
    下载压缩文件
    :param request:
    :param id: 数据库id
    :return:
    """
    file_name = request.GET.get('filename')
    path, name = os.path.split(file_name)
    file_path = os.path.join(BASE_DIR, file_name)
    if not os.path.isfile(file_path):  # 判断下载文件是否存在
        return HttpResponse("Sorry but Not Found the File")

    def file_iterator(file_path, chunk_size=1024):
        """
        文件生成器,防止文件过大，导致内存溢出
        :param file_path: 文件绝对路径
        :param chunk_size: 块大小
        :return: 生成器
        """
        with open(file_path, mode='rb') as f:
            while True:
                c = f.read(chunk_size)
                if c:
                    yield c
                else:
                    break

    try:
        # 设置响应头
        # StreamingHttpResponse将文件内容进行流式传输，数据量大可以用这个方法
        response = StreamingHttpResponse(file_iterator(file_path))
        # 以流的形式下载文件,这样可以实现任意格式的文件下载
        response['Content-Type'] = 'application/octet-stream'
        # Content-Disposition就是当用户想把请求所得的内容存为一个文件的时候提供一个默认的文件名
        # response['Content-Disposition'] = 'attachment;filename="{}"'.format(name)
        response["Content-Disposition"] = "attachment; filename*=UTF-8''{}".format(escape_uri_path(name))
    except:
        return HttpResponse("Sorry but Not Found the File")

    return response